home *** CD-ROM | disk | FTP | other *** search
- Path: news.belwue.de!uzwil!kuehl
- From: kuehl@uzwil.informatik.uni-konstanz.de (Dietmar Kuehl)
- Newsgroups: comp.lang.c++
- Subject: Re: How to read: operator overloaded <<
- Date: 21 Apr 1996 15:26:03 GMT
- Organization: FakultΣt fⁿr Mathematik und Informatik
- Message-ID: <4ldk2b$n9o@news.BelWue.DE>
- References: <4ldfpc$j0u@amanda.dorsai.org>
- Reply-To: dietmar.kuehl@uni-konstanz.de
- NNTP-Posting-Host: uzwil.informatik.uni-konstanz.de
- X-Newsreader: TIN [version 1.2 PL2]
-
- Jeff Yu (mongoose@dorsai.org) wrote:
- : Hi, I have hard time to understand the syntac of << operator overloaded
- : declaration. As it is stated in Lippman's C++ Primer, the << sample is
- : supposed to take TWO parameters: ostream& operator<<(ostream& os, String& s)
- : But when using it, the way is: cout<<"test"<<MyScreen<<endl;
- : Where is the second parameter if I consider the MyScreen as the first one?
-
- Operator notation is just a convenience for the programmer. An
- expression using operator syntax like this
-
- cout << "test";
-
- is converted (logically) by the compiler into an expression which uses
- the function call syntax, i.e. on of the following
-
- operator<< (out, str); // non-member function
- cout.operator<< (str); // member function
-
- As 'ostream &ostream::operator<< (char const *)' is defined, in the
- case of 'char const *' a member function is used for a string literal.
- For the class 'String' a non-member function is used. Thus, the
- function call notation of your expression looks something like this:
-
- operator << (operator<< (cout.operator<< ("test), MyScreen), endl);
-
- Thus, 'MyScreen' becomes the second argument to a call of
- 'operator<<()' where the first argument is the value returned from a
- call to 'cout.operator<< ("test")'.
-
- : What is the difference from ostream& operator << (String &s)?
-
- 'operator<< ()' is always a binary operator, thus 'operator << (String
- &s)' can only exist as a member function of an appropriate class, i.e.
- in the case of the IOStreams library 'ostream'. However, there is no
- such function implemented for a class 'String' thus, the only suitable
- overload for 'operator <<()' taking a 'String' is as binary, non-member
- function (do not try to implement it as a member of a class derived
- from 'ostream: It does not work nor is it intended to work).
- --
- dietmar.kuehl@uni-konstanz.de
- http://www.informatik.uni-konstanz.de/~kuehl/
- I am a realistic optimist - that's why I appear to be slightly pessimistic
-